package main

import (
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"github.com/kataras/iris/v12/sessions"
	"github.com/opentracing/opentracing-go/log"
	"goblog/config"
	"goblog/controllers"
	"goblog/daos"
	"goblog/middleware"
	"io"
	"os"

	//"goblog/middleware"
	"goblog/services"
	"goblog/tools"
	"time"
)

func main() {
	tools.InitGpWordFilter()
	tools.InitMgcFilter()

	logFile := tools.NewLogFile()
	defer logFile.Close()

	cfg,err := config.ParseConfig(tools.GetAppPath()+"/config/app.json")
    if err != nil{
		log.Error(err)
	}
	app := iris.Default()

	app.Logger().SetLevel(cfg.AppLogLevel).SetOutput(io.MultiWriter(logFile, os.Stdout))

	app.Use(middleware.CrsAuth())
	app.Use(middleware.JwtHandler().Serve)


	dbEngine,err := tools.OrmEngine(cfg)
	if err != nil {
		log.Error(err)
		panic(err)
	}

	//启用session
	sess := sessions.New(sessions.Config{
		Cookie:  "sessioncookie",
		Expires: 24 * time.Hour,
	})

	initRouter(app,dbEngine,sess)

	//6.启动服务
	_ = app.Run(
		iris.Addr(cfg.AppHost+":"+cfg.AppPort),
		iris.WithoutServerError(iris.ErrServerClosed),
		iris.WithOptimizations,
	)
}

func initRouter(app *iris.Application,dbEngine *tools.Orm,sess *sessions.Sessions){

	userDao := daos.NewUserDao(dbEngine)
	userService := services.NewUserService(userDao)
	userParty := app.Party("/user")
	userGroup := mvc.New(userParty)
	userGroup.Register(userService,sess.Start)
	userGroup.Handle(new(controllers.UserController))

	articleDao := daos.NewArticleDao(dbEngine)
	articleService := services.NewArticleService(articleDao)
	articleParty := app.Party("/article")
	articleGroup := mvc.New(articleParty)
	articleGroup.Register(articleService,userService,sess.Start)
	articleGroup.Handle(new(controllers.ArticleController))

	indexParty := app.Party("/index")
	indexGroup := mvc.New(indexParty)
	indexGroup.Register(userService,articleService,sess.Start)
	indexGroup.Handle(new(controllers.IndexController))

	spaceParty := app.Party("/space")
	spaceGroup := mvc.New(spaceParty)
	spaceGroup.Register(userService,articleService,sess.Start)
	spaceGroup.Handle(new(controllers.SpaceController))

	commentDao := daos.NewCommentDao(dbEngine)
	commentService := services.NewCommentService(commentDao)
	commParty := app.Party("/comment")
	commentGroup := mvc.New(commParty)
	commentGroup.Register(commentService,sess.Start)
	commentGroup.Handle(new(controllers.CommentController))

	// common
	common := app.Party("/")
	{
		common.Options("*", func(ctx iris.Context) {
			ctx.Next()
		})
	}
}
